// 3.1----------------数据逻辑
const data = {
	lrc:lrc,
	lrcArr:[]
}

/**
 * 格式化歌词，格式化对象结果为：{time:'时间',word:'歌词'}
 */
function parseLrc(){
	const lrcLines = data.lrc.split("\n");
	lrcLines.forEach(str =>{
		const parts = str.split(']');
		const lrcObj = {
			time:parseTime(parts[0].substring(1)),
			word:parts[1]
		}
		data.lrcArr.push(lrcObj);
	})
	console.log(data.lrcArr);
}

/**
 * 时间的格式化
 * @param {string} timeStr
 * @returns {number}
 */
function parseTime(timeStr){
	const parts = timeStr.split(':');
	return (parts[0]*60 + (+parts[1])).toFixed(2);
}

parseLrc();

// 3.2----------------界面逻辑
// 界面逻辑中需要使用的dom节点数据
const doms = {
	box:document.querySelector('.lrc_box'),
	audio:document.querySelector('.player_box'),
	ul:document.querySelector('.lrc_list')
}
// ui逻辑中需要操作的数据
const uiData = {
	currentIndex:-1,
	lrcBoxHeight:0,
	liHeight:0
}
/**
 * 初始化页面
 */
function initPage(){
	data.lrcArr.forEach(lrc =>{
		const li = document.createElement('li');
		li.classList.add('lrc_word');
		li.textContent = lrc.word;
		doms.ul.appendChild(li);
	})
	uiData.liHeight = doms.ul.children[0].clientHeight;
	uiData.lrcBoxHeight = doms.box.clientHeight;
	console.log(doms.box.clientHeight)
}
initPage();

/**
 * 找到对应高亮显示的歌词下标
 */
function findCurrentIndex(){
	const currentTime = doms.audio.currentTime;
	for (let index in data.lrcArr) {
		const lrc = data.lrcArr[index];
		if(lrc.time > currentTime){
			uiData.currentIndex = index - 1;
			return;
		}
	}
	uiData.currentIndex = data.lrcArr.length - 1;
}

/**
 * 高亮显示当前播放的歌词
 */
function showLrc(){
	findCurrentIndex();
	const oldLi = doms.ul.querySelector('.lrc_word_active');
	oldLi?oldLi.classList.remove('lrc_word_active'):1;
	if(uiData.currentIndex > -1){
		const li = doms.ul.children[uiData.currentIndex];
		li.classList.add('lrc_word_active');
		console.log(uiData.currentIndex)
	}
}

/**
 * 添加歌词滚动效果
 */
function setUlOffset(){
	showLrc();
	let height = uiData.liHeight*uiData.currentIndex+uiData.liHeight/2 - uiData.lrcBoxHeight/2;
	if(height < 0){
		height = 0;
	}
	doms.ul.style.transform = `translateY(-${height}px)`;
	console.log(height,uiData.liHeight,uiData.lrcBoxHeight);
}


// 3.3----------------事件逻辑
doms.audio.addEventListener('timeupdate',function(e){
	setUlOffset();
})

doms.audio.addEventListener('keydown',function(e){
	if(e.keyCode === 37){
		doms.audio.currentTime -= 5;
	}else if(e.keyCode === 39){
		doms.audio.currentTime += 5;
	}
})